package com.shanpin.shebao.admin.module.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.shanpin.core.http.JsonView;
import com.shanpin.core.http.MJsonView;
import com.shanpin.core.status.BaseStatus;
import com.shanpin.shebao.admin.controller.ResourceController;
import com.shanpin.shebao.admin.excel.ExcelService;
import com.shanpin.shebao.admin.module.user.model.Company;
import com.shanpin.shebao.admin.module.user.model.CompanyQueryForm;
import com.shanpin.shebao.common.LoginedService;
import com.shanpin.shebao.common.URI;
import com.shanpin.shebao.constant.QueryOperation;
import com.shanpin.shebao.model.report.MonthAmount;
import com.shanpin.shebao.utility.Criterition;
import com.shanpin.shebao.utility.MoreCriteria;
import com.shanpin.shebao.utility.PageModel;

/**
 * 用户管理-企业管理
 * 企业管理控制器
 */
@Controller
public class CompanyController extends ResourceController {
	
	@Autowired
	private ExcelService excelService;
	@Autowired
	private CompanyService companyService;
	
	/**
	 * 用户管理-企业管理
	 * 查询列表
	 */
	@RequestMapping(URI.COMPANY_MANAGER)
	public ModelAndView queryPageBy(PageModel page, @ModelAttribute CompanyQueryForm form, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("user/company_manage");
		
		MoreCriteria<String, Criterition> mc = new MoreCriteria<String, Criterition>();
		List<String> ulist = buildForm(form, mc, request);
		mv.addObject("optUserList", ulist);
		
		int pageSize = 20;
		int pageNo = page.getPageNo();

		PageModel pageModel = companyService.queryPage(pageNo, pageSize, mc, form.getCalled());
		mv.addObject("pageModel", pageModel);
		
		mv.addObject("manager_uri", URI.SBA + URI.COMPANY_MANAGER);
		mv.addObject("manager_export_uri", URI.SBA + URI.COMPANY_EXPORT);
		mv.addObject("phonecall_uri", URI.SBA + URI.COMPANY_NEW_PHONECALL);
		mv.addObject("load_notes_uri", URI.SBA + URI.COMPANY_NEW_LOADNOTES);
		mv.addObject("new_ent_uri", URI.SBA + URI.COMPANY_NEW_ENTERPRISE);
		mv.addObject("edit_contact_uri", URI.SBA + URI.COMPANY_EDIT_CONTACT);
		mv.addObject("list_contract_uri", URI.SBA + URI.COMPANY_LIST_CONTRACT);
		mv.addObject("upload_contract_uri", URI.SBA + URI.COMPANY_UPLOAD_CONTRACT);
		mv.addObject("download_contract_uri", URI.SBA + URI.COMPANY_DOWNLOAD_CONTRACT);
		mv.addObject("del_contract_uri", URI.SBA + URI.COMPANY_DELETE_CONTRACT);
		return mv;
	}
	
	
	private List<String> buildForm(CompanyQueryForm form, MoreCriteria<String, Criterition> mc, HttpServletRequest request) {
		Map<String, Criterition> pair = (Map<String, Criterition>) mc.getPair();
		if(form.getName() != null && !"".equals(form.getName())) {
			Criterition c = new Criterition("company.enName", "%"+form.getName().trim()+"%", QueryOperation.LIKE, QueryOperation.AND);
			pair.put("enName", c);
		}
		
		if(form.getPhone() != null && !"".equals(form.getPhone())) {
			Criterition c = new Criterition("company.contact_phone", form.getPhone().trim(), QueryOperation.EQ, QueryOperation.AND);
			pair.put("contact_phone", c);
		}
		if(StringUtils.isNotBlank(form.getOpt_sign())) {
			if ("2".equals(form.getOpt_sign())) {
				Criterition c = new Criterition("company.contract_num", "0", QueryOperation.GT, QueryOperation.AND);
				pair.put("contract_num", c);
			} else {
				QueryOperation qo = "1".equals(form.getOpt_sign()) ? QueryOperation.GE : QueryOperation.EQ;
				Criterition c = new Criterition("company.opt_sign", form.getOpt_sign().trim(), qo, QueryOperation.AND);
				pair.put("opt_sign", c);
			}
		}
		if (StringUtils.isNotBlank(form.getOpt_user())) {
			Criterition c = new Criterition("company.opt_user", form.getOpt_user().trim(), QueryOperation.EQ, QueryOperation.AND);
			pair.put("opt_user", c);
		}
		
		String opt_user = getLoginUser(request);
		String areas = companyService.getAreas(opt_user);
		List<String> ulist = null;
		if ("ALL".equals(areas) || opt_user.equals("lilihua")) {	// 查看全部企业登记
			ulist = companyService.entUserNames();
			
		} else if (StringUtils.isNotBlank(areas)) {
			Criterition c = new Criterition("company.opt_user", opt_user, QueryOperation.EQ, QueryOperation.AND);
			pair.put("opt_user", c);
			ulist = new ArrayList<>(1);
			ulist.add(opt_user);
		}
		return ulist;
	}
	
	
	@RequestMapping(URI.COMPANY_EXPORT)
	public void exportManagerData(CompanyQueryForm form, HttpServletRequest request, HttpServletResponse resp) throws IOException {
		MoreCriteria<String, Criterition> mc = new MoreCriteria<String, Criterition>();
		buildForm(form, mc, request);
		List<Company> companys = companyService.export(mc, form.getCalled());
		String[] headers = { "公司名称", "业务", "所在城市", 
				 "员工数", "联系人", "联系电话",
				 "用户备注", "生成时间", "最新回访",
				 "回访时间"};
		String[] fields = { "name", "demand", "city",
				"employees", "contact_name", "contact_phone",
				"remark", "gen_time", "phone_result",
				"phone_time"};
		resp.setContentType("application/vnd.ms-excel;charset=utf-8");
		resp.setHeader("Content-disposition", "attachment;filename=companyUser.xls");
		ServletOutputStream servletOutputStream = resp.getOutputStream();
		excelService.exportExcel("企业用户", headers,fields, companys, servletOutputStream);
		servletOutputStream.close();
	}
	

	@RequestMapping(value=URI.COMPANY_NEW_LOADNOTES, method=RequestMethod.POST)
	public ModelAndView loadNotes(int id) throws IOException {
		return MJsonView.ok(companyService.loadNotes(id));
	}
	
	/**
	 * 企业登记的回访
	 */
	@RequestMapping(value=URI.COMPANY_NEW_PHONECALL, method=RequestMethod.POST)
	public void phoneCall(HttpServletRequest request, HttpServletResponse response, 
			int id, String result, int sms, String sms_content) throws IOException {
		if (StringUtils.isBlank(result)) {
			JsonView.fail("回访结果需要填写").write(response);
			return;
		}
		if (id < 1) {
			JsonView.fail("回访结果的ID需要有值").write(response);
			return;
		}
		String opt_user = getLoginUser(request);
		String areas = companyService.getAreas(opt_user);
		if (StringUtils.isBlank(areas)) {
			JsonView.fail("回访登记需要权限").write(response);
			return;
		}
		boolean r = companyService.phoneCall(id, result, sms, sms_content, opt_user);
		if (r) {
			JsonView.ok().write(response);
			return;
		}
		JsonView.fail("回访登记出现异常").write(response);
		return;
	}
	
	
	@RequestMapping(value=URI.COMPANY_EDIT_CONTACT, method=RequestMethod.POST)
	public void update_contact(HttpServletRequest request, HttpServletResponse response, 
			int id, String contact_wechat, String contact_qq, String contact_mail) throws IOException {
		if (id < 1) {
			JsonView.fail("ID需要有值").write(response);
			return;
		}
		String opt_user = getLoginUser(request);
		String areas = companyService.getAreas(opt_user);
		if (!"super".equals(opt_user) && StringUtils.isBlank(areas)) {
			JsonView.fail("回访登记需要权限").write(response);
			return;
		}
		try {
			companyService.updateContact(id, contact_wechat, contact_qq, contact_mail, opt_user);
			JsonView.ok().write(response);
			return;
		} catch (Exception e) {
			JsonView.fail(e.getMessage()).write(response);
		}
	}
	
	
	/**
	 * 手动登记企业
	 */
	@RequestMapping(value=URI.COMPANY_NEW_ENTERPRISE, method=RequestMethod.POST)
	public ModelAndView entSign(String city, String enName, String contact_name, 
			String contact_phone, String employees, String demand, 
			String remark, String opt_user, HttpServletRequest request) throws IOException {
		if (StringUtils.isBlank(city)) {
			return MJsonView.resp(BaseStatus.PARAM_INVALID, "城市需要有效值");
		} else if (StringUtils.isBlank(enName)) {
			return MJsonView.resp(BaseStatus.PARAM_INVALID, "企业名称需要有效值");
		} else if (StringUtils.isBlank(contact_name)) {
			return MJsonView.resp(BaseStatus.PARAM_INVALID, "联系人需要有效值");
		} else if (StringUtils.isBlank(contact_phone)) {
			return MJsonView.resp(BaseStatus.PARAM_INVALID, "需要填写联系人电话");
		} else if (StringUtils.isBlank(employees)) {
			return MJsonView.resp(BaseStatus.PARAM_INVALID, "需要填写公司人数");
		} else if (StringUtils.isBlank(demand)) {
			return MJsonView.resp(BaseStatus.PARAM_INVALID, "需要选择业务需求");
		} else if (StringUtils.isBlank(remark)) {
			return MJsonView.resp(BaseStatus.PARAM_INVALID, "需要填写备注");
		}
		String sign_user = getLoginUser(request);	// 登记人员
		if (StringUtils.isBlank(opt_user)) {
			opt_user = sign_user;
		}
		boolean ret = companyService.entSign(city, enName, contact_name, 
				contact_phone, employees, demand, remark, opt_user, sign_user);
		return ret ? MJsonView.ok() : MJsonView.fail();
	}
	
	/**
	 * 企业登记的回访
	 */
	@RequestMapping(value="/delete", method=RequestMethod.GET)
	public void delete(int id, HttpServletResponse response) throws IOException {
		if (id  < 1) {
			JsonView.fail("无效的id").write(response);
			return;
		}
		boolean r = companyService.delete(id);
		if (r) {
			JsonView.ok().write(response);
			return;
		}
		JsonView.fail().write(response);
		return;
	}
	
	
	
	@RequestMapping(URI.COMPANY_LOAD_COUNT)
	public ModelAndView entInfo(HttpServletRequest req) {
		String login_user = LoginedService.getUsername();
		return MJsonView.ok(companyService.hasEntpriseReg(login_user));
	}
	
	
	@RequestMapping(URI.COMPANY_USER_SETTING_MANAGER)
	public ModelAndView userSetting(HttpServletRequest request) throws IOException {
		String opt_user = getLoginUser(request);
		if ("super".equals(opt_user) || "lilihua".equals(opt_user)) {
			ModelAndView mav = new ModelAndView("user/company_user_setting");
			mav.addObject("users", companyService.entUsers());

			mav.addObject("manager_uri", URI.SBA + URI.COMPANY_USER_SETTING_MANAGER);
			mav.addObject("setting_uri", URI.SBA + URI.COMPANY_USER_SETTING);
			mav.addObject("load_uri", URI.SBA + URI.COMPANY_USER_SETTING_LOAD);
			return mav;
		}
		return MJsonView.fail("禁止访问，需要访问权限请联系管理员。");
	}

	@RequestMapping(URI.COMPANY_USER_SETTING_LOAD)
	public ModelAndView loadSetting(String name) throws IOException {
		if (StringUtils.isNotBlank(name)) {
			return MJsonView.ok(companyService.getAreas(name));
		}
		return MJsonView.resp(BaseStatus.PARAM_INVALID, "业务员帐号是空的。");
	}
	

	@RequestMapping(URI.COMPANY_USER_SETTING)
	public ModelAndView saveSetting(String uname, String areas, HttpServletRequest request) throws IOException {
		if (StringUtils.isBlank(uname)) {
			return MJsonView.resp(BaseStatus.PARAM_INVALID, "业务员帐号是空的。");
		} else if (StringUtils.isBlank(areas)) {
//			return MJsonView.resp(BaseStatus.PARAM_INVALID, "区域是空的。"); // 删除用户的配置
		}
		String opt_user = getLoginUser(request);
		boolean ret = false;
		if ("super".equals(opt_user) || "admin".equals(opt_user)) {
			ret = companyService.saveSetting(uname, areas);
		}
		return ret? MJsonView.ok() : MJsonView.fail();
	}
	
}
